<template>
  <div class="tool-return-add">
    <section class="hero-wrapper">
      <div class="page-header">
        <div>
          <div class="page-title">
            <h2>工具归还单</h2>
            <p>请完善归还基础信息和明细，确保可追溯性与准确性。</p>
          </div>
          <div class="page-tags">
            <el-tag size="small" effect="dark" type="info">工具管理</el-tag>
            <el-tag size="small" effect="plain" type="primary">归还作业</el-tag>
            <el-tag size="small" effect="plain" type="success">智能表单</el-tag>
          </div>
        </div>
        <div class="header-meta">
          <div class="meta-item status-pill">
            <span class="meta-label">当前状态</span>
            <div class="meta-status">
              <el-tag :type="statusTagType" size="small">{{
                statusText
              }}</el-tag>
              <span class="status-hint">{{
                progressStep === 2 ? "可提交" : "待完善"
              }}</span>
            </div>
          </div>
          <div class="meta-item">
            <span class="meta-label">归还编号</span>
            <span class="meta-value">{{ form.returnNo || "待生成" }}</span>
          </div>
          <div class="meta-item">
            <span class="meta-label">明细总数</span>
            <span class="meta-value accent">{{ detailTotal }}</span>
          </div>
        </div>
        <div class="page-actions">
          <el-button
            size="default"
            plain
            type="primary"
            @click="handleForceGenerate"
            :icon="Refresh"
            class="action-btn"
          >
            重新生成单号
          </el-button>
          <el-button
            size="default"
            type="primary"
            @click="handleAddDetail"
            :icon="Plus"
            class="action-btn primary-btn"
          >
            快速添加明细
          </el-button>
        </div>
      </div>
      <div class="progress-steps">
        <el-steps :active="progressStep" finish-status="success" align-center>
          <el-step title="基础信息" description="填写编号与人员" />
          <el-step title="归还明细" description="完善工具明细" />
          <el-step title="提交确认" description="校对并保存" />
        </el-steps>
      </div>
      <el-alert
        class="tips-alert"
        type="info"
        show-icon
        :closable="false"
        title="填写提示"
        description="系统支持自动生成单号，建议优先完成基础信息，再批量维护归还明细，可通过右上角快速查看当前完成度。"
      />
      <div class="insight-panel">
        <div class="insight-card primary">
          <div class="insight-icon">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="insight-meta">
            <span class="insight-label">归还总数量</span>
            <span class="insight-value">{{ detailTotal }}</span>
          </div>
          <el-progress
            :percentage="Math.min(detailTotal * 10, 100)"
            stroke-width="6"
            :show-text="false"
          />
        </div>
        <div class="insight-card">
          <div class="insight-icon">
            <el-icon><Collection /></el-icon>
          </div>
          <div class="insight-meta">
            <span class="insight-label">明细完整度</span>
            <span class="insight-value">{{ detailCoverage }}%</span>
          </div>
          <p class="insight-tip">
            {{ detailCoverage >= 80 ? "数据较完整" : "还有字段待填写" }}
          </p>
        </div>
        <div class="insight-card">
          <div class="insight-icon">
            <el-icon><Finished /></el-icon>
          </div>
          <div class="insight-meta">
            <span class="insight-label">选中占比</span>
            <span class="insight-value">{{ selectedRate }}%</span>
          </div>
          <p class="insight-tip">用于批量操作的明细占比</p>
        </div>
      </div>
    </section>
    <el-card shadow="never" class="section-card">
      <template #header>
        <div class="section-header">
          <div class="section-title">
            <el-icon class="section-icon"><Document /></el-icon>
            <span>基础信息</span>
          </div>
          <p class="section-subtitle">填写归还单基础信息并选择对应人员</p>
        </div>
      </template>
      <el-form :model="form" label-width="90px" class="base-form">
        <el-row :gutter="12">
          <el-col :span="8">
            <el-form-item label="归还编号">
              <el-input
                v-model="form.returnNo"
                :disabled="form.autoNo"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4" style="display: flex; align-items: center">
            <el-form-item label-width="0">
              <el-switch v-model="form.autoNo" @change="handleAutoNoChange" />
              <span style="margin-left: 8px; color: #909399">系统编号</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="归还名称" required>
              <el-input v-model="form.returnName" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="8">
            <el-form-item label="归还时间">
              <el-date-picker
                v-model="form.returnTime"
                type="datetime"
                value-format="YYYY-MM-DDTHH:mm:ss"
                placeholder="请选择"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="归还人">
              <div class="returner-input">
                <el-input
                  v-model="form.returnerName"
                  placeholder="请选择归还人"
                  disabled
                />
                <el-tooltip content="选择归还人" placement="top">
                  <el-button
                    class="returner-picker-btn"
                    circle
                    type="primary"
                    :loading="userLoading"
                    @click="openReturnerDialog"
                  >
                    <el-icon><User /></el-icon>
                  </el-button>
                </el-tooltip>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联领用单">
              <el-select
                v-model="form.borrowOrderId"
                placeholder="请选择"
                clearable
                filterable
                @change="handleBorrowOrderChange"
              >
                <el-option
                  v-for="o in borrowOrderOptions"
                  :key="o.value"
                  :label="o.label"
                  :value="o.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="8">
            <el-form-item label="归还状态">
              <el-select v-model="form.returnStatus" placeholder="请选择">
                <el-option
                  v-for="o in statusOptions"
                  :key="o.value"
                  :label="o.label"
                  :value="o.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="never" class="section-card">
      <template #header>
        <div class="section-header">
          <div class="section-title">
            <el-icon class="section-icon"><List /></el-icon>
            <span>归还明细</span>
          </div>
          <p class="section-subtitle">维护每一条归还记录，支持批量操作</p>
        </div>
      </template>
      <div class="detail-toolbar">
        <div class="toolbar-left">
          <el-button
            type="primary"
            size="default"
            @click="handleAddDetail"
            :icon="Plus"
            class="toolbar-btn"
            >添加明细</el-button
          >
          <el-button
            size="default"
            @click="handleRemoveDetail"
            :icon="Delete"
            class="toolbar-btn"
            :disabled="!selectedDetails.length"
            >批量移除</el-button
          >
        </div>
        <div class="toolbar-right">
          <el-tag type="info" size="small" effect="plain" class="toolbar-tag">
            已选择 <strong>{{ selectedDetails.length }}</strong> 条
          </el-tag>
          <el-divider direction="vertical" />
          <el-tag
            type="success"
            size="small"
            effect="plain"
            class="toolbar-tag"
          >
            归还总数：<strong>{{ detailTotal }}</strong>
          </el-tag>
          <el-divider direction="vertical" />
          <el-tag
            :type="detailCoverage >= 80 ? 'success' : 'warning'"
            size="small"
            effect="dark"
            class="toolbar-tag"
            >完整度 {{ detailCoverage }}%</el-tag
          >
        </div>
      </div>
      <el-table
        class="detail-table"
        :data="form.details"
        size="small"
        border
        stripe
        empty-text="暂未添加明细"
        highlight-current-row
        :row-class-name="detailRowClassName"
        @selection-change="handleDetailSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column label="工装夹具" min-width="200">
          <template #default="{ row }">
            <el-select
              v-model="row.toolFixtureId"
              placeholder="选择工装夹具"
              filterable
              clearable
              style="width: 100%"
              @change="(val: any) => handleFixtureChange(row, val)"
            >
              <el-option
                v-for="item in fixtureOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="库位" min-width="180">
          <template #default="{ row }">
            <el-select
              v-model="row.storageLocationId"
              placeholder="选择库位"
              filterable
              clearable
              style="width: 100%"
              @change="(val: any) => handleSeatChange(row, val)"
            >
              <el-option
                v-for="item in seatOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="领用明细ID" min-width="180">
          <template #default="{ row }">
            <el-select
              v-model="row.borrowDetailId"
              placeholder="选择领用明细"
              filterable
              clearable
              style="width: 100%"
              @change="(val: any) => handleBorrowDetailIdChange(row, val)"
            >
              <el-option
                v-for="item in borrowDetailOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="归还数量" width="120" align="center">
          <template #default="{ row }">
            <el-input-number v-model="row.returnCount" :min="1" />
          </template>
        </el-table-column>
        <el-table-column label="工具状态" min-width="160">
          <template #default="{ row }">
            <el-select
              v-model="row.toolStatusWhenReturn"
              placeholder="选择状态"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in toolStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="验收人" min-width="140">
          <template #default="{ row }">
            <el-select
              v-model="row.checkerId"
              placeholder="请选择"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="o in checkerOptions"
                :key="o.value"
                :label="o.label"
                :value="o.value"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="200">
          <template #default="{ row }">
            <el-input v-model="row.remarkDetail" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="{ $index }">
            <el-button
              type="danger"
              link
              size="small"
              @click="removeDetailAt($index)"
              :icon="Delete"
              class="delete-btn"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="summary-line">
        <el-tag effect="dark" size="small" type="info">归还总数</el-tag>
        <span class="summary-value">{{ detailTotal }}</span>
      </div>
    </el-card>

    <div class="footer-actions">
      <el-button
        @click="handleCancel"
        size="default"
        class="footer-btn"
        :icon="Close"
        >关闭</el-button
      >
      <el-button
        type="primary"
        :loading="saving"
        @click="handleSubmit"
        size="default"
        class="footer-btn submit-btn"
        :icon="Check"
      >
        {{ saving ? "保存中..." : "确定保存" }}
      </el-button>
    </div>
    <el-dialog
      v-model="userDialogVisible"
      title="选择归还人"
      width="720"
      class="user-dialog"
    >
      <template #header>
        <div class="dialog-header">
          <el-icon class="dialog-icon"><User /></el-icon>
          <span>选择归还人</span>
        </div>
      </template>
      <div class="manager-search">
        <el-input
          v-model="userKeyword"
          placeholder="请输入姓名/工号/部门关键字"
          clearable
          size="default"
          class="search-input"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <el-table
        :data="filteredUsers"
        v-loading="userLoading"
        height="360px"
        class="user-table"
        stripe
      >
        <el-table-column prop="username" label="姓名" width="140">
          <template #default="scope">
            <div class="user-name-cell">
              <el-icon class="user-icon"><User /></el-icon>
              <span>{{ scope.row.username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="usernumber" label="工号" width="140" />
        <el-table-column prop="organname" label="部门" />
        <el-table-column prop="phone" label="联系方式" width="140" />
        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleReturnerPick(scope.row)"
              :icon="Check"
              class="select-btn"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import {
  Search,
  User,
  Document,
  List,
  TrendCharts,
  Collection,
  Finished,
  Plus,
  Refresh,
  Delete,
  Close,
  Check,
} from "@element-plus/icons-vue";
import { useRoute, useRouter } from "vue-router";
import https from "@/Http/http";

interface DetailRow {
  id?: number;
  borrowDetailId: number | string;
  toolFixtureId?: number;
  toolFixtureName?: string;
  storageLocationId?: number;
  storageLocationName?: string;
  returnCount: number | string;
  toolStatusWhenReturn: number | string;
  checkerId: number | string;
  remarkDetail?: string;
}

const route = useRoute();
const router = useRouter();

const userDialogVisible = ref(false);
const userKeyword = ref("");
const userList = ref<UserDto[]>([]);
const userLoading = ref(false);
const filteredUsers = computed(() => {
  const keyword = userKeyword.value.trim().toLowerCase();
  if (!keyword) return userList.value;
  return userList.value.filter((item) =>
    ["username", "usernumber", "organname"]
      .map((key) => item[key as keyof UserDto]?.toString().toLowerCase() ?? "")
      .some((text) => text.includes(keyword))
  );
});

const returnerOptions = ref<{ label: string; value: number }[]>([]);
const checkerOptions = ref<{ label: string; value: number }[]>([]);
const borrowOrderOptions = ref<{ label: string; value: number }[]>([]);
const fixtureOptions = ref<
  { label: string; value: number; seatId?: number; seatName?: string }[]
>([]);
const seatOptions = ref<{ label: string; value: number }[]>([]);
const borrowDetailOptions = ref<
  {
    label: string;
    value: number;
    toolFixtureId?: number;
    toolFixtureName?: string;
    storageLocationId?: number;
    storageLocationName?: string;
  }[]
>([]);
const statusOptions = [
  { label: "待确认", value: 0 },
  { label: "已完成", value: 1 },
];
const toolStatusOptions = [
  { label: "完好", value: 0 },
  { label: "需维修", value: 1 },
  { label: "待检修", value: 2 },
];

interface UserDto {
  id: number;
  username: string;
  usernumber?: string;
  organid?: number;
  organname?: string;
  phone?: string;
}

const form = reactive({
  id: 0,
  returnNo: "",
  autoNo: false,
  returnName: "",
  returnerId: "" as any,
  returnerName: "",
  borrowOrderId: "" as any,
  returnTime: "",
  returnStatus: 0,
  remark: "",
  details: [] as DetailRow[],
});

const saving = ref(false);
const selectedDetails = ref<DetailRow[]>([]);
const detailTotal = computed(() =>
  form.details.reduce((s, d) => s + Number(d.returnCount || 0), 0)
);
const detailCoverage = computed(() => {
  if (!form.details.length) return 0;
  const filled = form.details.filter(
    (item) =>
      Number(item.borrowDetailId) > 0 &&
      Number(item.toolFixtureId) > 0 &&
      Number(item.storageLocationId) > 0
  ).length;
  return Math.round((filled / form.details.length) * 100);
});
const selectedRate = computed(() => {
  if (!form.details.length) return 0;
  return Math.round((selectedDetails.value.length / form.details.length) * 100);
});
const progressStep = computed(() => {
  if (!form.returnName || !form.returnTime || !form.returnerId) return 0;
  if (!form.details.length) return 1;
  return 2;
});
const statusText = computed(() => {
  const hit = statusOptions.find((item) => item.value === form.returnStatus);
  return hit?.label ?? "未知状态";
});
const statusTagType = computed(() =>
  form.returnStatus === 1 ? "success" : "warning"
);

const autoGeneratedReturnNo = ref("");
const buildTimeBasedReturnCode = (prefix = "GH") => {
  const now = new Date();
  const HH = String(now.getHours()).padStart(2, "0");
  const mm = String(now.getMinutes()).padStart(2, "0");
  const ss = String(now.getSeconds()).padStart(2, "0");
  return `${prefix}${HH}${mm}${ss}`;
};

const generateTimeBasedReturnNo = () => {
  const code = buildTimeBasedReturnCode();
  form.returnNo = code;
  autoGeneratedReturnNo.value = code;
};

const handleAutoNoChange = (v: boolean) => {
  if (v) {
    generateTimeBasedReturnNo();
  } else {
    if (form.returnNo === autoGeneratedReturnNo.value) {
      form.returnNo = "";
    }
    autoGeneratedReturnNo.value = "";
  }
};

const handleForceGenerate = () => {
  if (!form.autoNo) {
    form.autoNo = true;
  }
  generateTimeBasedReturnNo();
  ElMessage.success("已生成新的归还编号");
};

const fetchReturnerList = async () => {
  if (userLoading.value) return;
  userLoading.value = true;
  try {
    const res = await https.Reads.get("/RBAC/ShowUser", {
      params: { pageindex: 1, pagesize: 1000 },
    });
    const list = res.data?.data ?? [];
    userList.value = list;
    returnerOptions.value = list.map((x: UserDto) => ({
      label: x.username,
      value: x.id,
    }));
    checkerOptions.value = list.map((x: UserDto) => ({
      label: x.username,
      value: x.id,
    }));
  } finally {
    userLoading.value = false;
  }
};

const openReturnerDialog = () => {
  userDialogVisible.value = true;
  if (!userList.value.length) {
    fetchReturnerList();
  }
};

const getReturnerNameById = (id: number | string) => {
  const numId = Number(id);
  if (!numId) return "";
  const hit = userList.value.find((x) => x.id === numId);
  return hit?.username || "";
};

const handleAddDetail = () => {
  form.details.push({
    id: 0,
    borrowDetailId: "",
    toolFixtureId: 0,
    toolFixtureName: "",
    storageLocationId: 0,
    storageLocationName: "",
    returnCount: 1,
    toolStatusWhenReturn: "",
    checkerId: "",
    remarkDetail: "",
  });
};

const removeDetailAt = (idx: number) => {
  form.details.splice(idx, 1);
};

const handleDetailSelectionChange = (rows: DetailRow[]) => {
  selectedDetails.value = rows;
};

const detailRowClassName = ({
  row,
  rowIndex,
}: {
  row: DetailRow;
  rowIndex: number;
}) => {
  if (
    !Number(row.borrowDetailId) ||
    !Number(row.toolFixtureId) ||
    !Number(row.storageLocationId)
  ) {
    return "detail-row-warning";
  }
  return rowIndex % 2 === 0 ? "detail-row-even" : "detail-row-odd";
};

// 工装夹具选择变更
const handleFixtureChange = (row: DetailRow, value: number | null) => {
  const hit = fixtureOptions.value.find((x) => x.value === value);
  row.toolFixtureName = hit?.label || "";
  // 如果工装夹具有默认库位，且当前行没有库位，则自动填充
  if (hit?.seatId && !row.storageLocationId) {
    row.storageLocationId = hit.seatId;
    const seatHit = seatOptions.value.find((x) => x.value === hit.seatId);
    row.storageLocationName = seatHit?.label || "";
  }
};

// 库位选择变更
const handleSeatChange = (row: DetailRow, value: number | null) => {
  row.storageLocationId = value || 0;
  const hit = seatOptions.value.find((x) => x.value === value);
  row.storageLocationName = hit?.label || "";
};

const handleReturnerPick = (row: UserDto) => {
  form.returnerId = row.id;
  form.returnerName = row.username || "";
  userDialogVisible.value = false;
};

// 领用明细ID选择变更，自动填充工具和库位信息
const handleBorrowDetailIdChange = (row: DetailRow, value: number | null) => {
  if (!value || Number(value) <= 0) {
    row.toolFixtureId = 0;
    row.toolFixtureName = "";
    row.storageLocationId = 0;
    row.storageLocationName = "";
    return;
  }
  // 从下拉选项中查找对应的明细信息
  const detail = borrowDetailOptions.value.find(
    (d) => d.value === Number(value)
  );
  if (detail) {
    // 填充工具和库位信息
    row.toolFixtureId = detail.toolFixtureId || 0;
    row.toolFixtureName = detail.toolFixtureName || "";
    row.storageLocationId = detail.storageLocationId || 0;
    row.storageLocationName = detail.storageLocationName || "";
  }
};

// 刷新明细标签（根据ID填充名称）
const refreshDetailLabels = () => {
  form.details.forEach((row) => {
    if (row.toolFixtureId) {
      const fixture = fixtureOptions.value.find(
        (x) => x.value === row.toolFixtureId
      );
      if (fixture) {
        row.toolFixtureName = fixture.label;
      }
    }
    if (row.storageLocationId) {
      const seat = seatOptions.value.find(
        (x) => x.value === row.storageLocationId
      );
      if (seat) {
        row.storageLocationName = seat.label;
      }
    }
  });
};

const handleRemoveDetail = () => {
  if (!selectedDetails.value.length) {
    ElMessage.warning("请先选择明细");
    return;
  }
  form.details = form.details.filter(
    (d) => !selectedDetails.value.includes(d)
  ) as any;
};

const toAddPayload = () => ({
  ReturnNo: form.returnNo,
  ReturnName: form.returnName,
  BorrowOrderId: Number(form.borrowOrderId) || 0,
  ReturnerId: Number(form.returnerId) || 0,
  ReturnTime: form.returnTime || new Date().toISOString(),
  ReturnStatus: Number(form.returnStatus) || 0,
  Remark: form.remark || "",
  tool_Return_OrderDetails: form.details.map((d) => ({
    ReturnOrderId: 0,
    BorrowDetailId: Number(d.borrowDetailId) || 0,
    ToolFixtureId: Number(d.toolFixtureId) || 0,
    StorageLocationId: Number(d.storageLocationId) || 0,
    ReturnCount: Number(d.returnCount) || 0,
    ToolStatusWhenReturn: Number(d.toolStatusWhenReturn) || 0,
    CheckerId: Number(d.checkerId) || 0,
    RemarkDetali: d.remarkDetail || "",
  })),
});

const toUpdatePayload = () => ({
  id: Number(form.id) || 0,
  ReturnNo: form.returnNo,
  ReturnName: form.returnName,
  BorrowOrderId: Number(form.borrowOrderId) || 0,
  ReturnerId: Number(form.returnerId) || 0,
  ReturnTime: form.returnTime || new Date().toISOString(),
  ReturnStatus: Number(form.returnStatus) || 0,
  Remark: form.remark || "",
  tool_Return_OrderDetails: form.details.map((d) => ({
    id: Number(d.id) || 0,
    ReturnOrderId: Number(form.id) || 0,
    BorrowDetailId: Number(d.borrowDetailId) || 0,
    ToolFixtureId: Number(d.toolFixtureId) || 0,
    StorageLocationId: Number(d.storageLocationId) || 0,
    ReturnCount: Number(d.returnCount) || 0,
    ToolStatusWhenReturn: Number(d.toolStatusWhenReturn) || 0,
    CheckerId: Number(d.checkerId) || 0,
    RemarkDetali: d.remarkDetail || "",
  })),
});

const handleSubmit = async () => {
  if (form.autoNo && !form.returnNo) generateTimeBasedReturnNo();
  if (!form.returnName) {
    ElMessage.error("请填写归还名称");
    return;
  }
  if (!form.details.length) {
    ElMessage.error("请至少添加一条归还明细");
    return;
  }
  try {
    saving.value = true;
    if (form.id && Number(form.id) > 0) {
      const res = await https.Writes.put(
        "/Appliance/Tool_return_orderUpdate",
        toUpdatePayload()
      );
      if (res.data && res.data.code === 1) ElMessage.success("编辑成功");
      else ElMessage.success("编辑提交完成");
    } else {
      const res = await https.Writes.post(
        "/Appliance/Tool_return_orderAdd",
        toAddPayload()
      );
      if (res.data && res.data.code === 1) ElMessage.success("新增成功");
      else ElMessage.success("新增提交完成");
    }
    router.push("/Toolreturnorderlist");
  } catch (e) {
    ElMessage.error("保存失败，请稍后重试");
  } finally {
    saving.value = false;
  }
};

const handleCancel = () => {
  router.push("/Toolreturnorderlist");
};

// 加载领用单列表
const loadBorrowOrders = async () => {
  try {
    const res = await https.Reads.get("/Applicae/Toolborrowheaderlist", {
      params: { Pageindex: 1, PageSize: 1000 },
    });
    const data = res.data?.data ?? [];
    borrowOrderOptions.value = (data || []).map((x: any) => ({
      label: `${x.borrowNo} - ${x.borrowName}`,
      value: x.id,
    }));
  } catch (e) {
    // 加载失败
  }
};

// 加载工装夹具列表
const fetchFixtureOptions = async () => {
  try {
    const res = await https.Reads.get("/Applicae/work_fixturelist", {
      params: { Pageindex: 1, PageSize: 1000 },
    });
    const list = res.data?.data ?? [];
    fixtureOptions.value = list.map((item: any) => ({
      label: item.work_fixturename,
      value: item.id,
      seatId: item.work_fixtureseatid,
      seatName: item.work_fixtureseatname,
    }));
    refreshDetailLabels();
  } catch {
    fixtureOptions.value = [];
  }
};

// 加载库位列表
const fetchSeatOptions = async () => {
  try {
    const res = await https.Reads.get("/Applicae/Work_fixtureseatlist", {
      params: { Pageindex: 1, PageSize: 1000 },
    });
    const list = res.data?.data ?? [];
    seatOptions.value = list.map((item: any) => ({
      label: item.work_fixtureseatname,
      value: item.id,
    }));
    refreshDetailLabels();
  } catch {
    seatOptions.value = [];
  }
};

// 加载领用明细列表（根据选中的领用单）
const loadBorrowDetails = async () => {
  if (!form.borrowOrderId || Number(form.borrowOrderId) <= 0) {
    borrowDetailOptions.value = [];
    return;
  }
  try {
    const res = await https.Reads.get("/Applicae/ToolborrowheaderDetail", {
      params: { id: form.borrowOrderId },
    });
    const data = res.data?.data;
    if (data && data.details) {
      borrowDetailOptions.value = data.details.map((detail: any) => ({
        label: `${detail.toolFixtureName || "未知工具"} - ${
          detail.storageLocationName || "未知库位"
        } (ID: ${detail.id})`,
        value: detail.id,
        toolFixtureId: detail.toolFixtureId,
        toolFixtureName: detail.toolFixtureName,
        storageLocationId: detail.storageLocationId,
        storageLocationName: detail.storageLocationName,
      }));
    } else {
      borrowDetailOptions.value = [];
    }
  } catch (e) {
    borrowDetailOptions.value = [];
    ElMessage.error("加载领用明细失败");
  }
};

// 监听领用单变化，重新加载领用明细
const handleBorrowOrderChange = () => {
  loadBorrowDetails();
  // 清空现有明细的领用明细ID
  form.details.forEach((row) => {
    row.borrowDetailId = "";
    row.toolFixtureId = 0;
    row.toolFixtureName = "";
    row.storageLocationId = 0;
    row.storageLocationName = "";
  });
};

// 加载归还详情（编辑时使用）
const loadReturnOrderDetail = async (id: number) => {
  try {
    const res = await https.Reads.get("/Applicae/ToolReturnOrderDetail", {
      params: { id },
    });
    const data = res.data?.data;
    if (data) {
      // 回填基础信息
      form.returnNo = data.returnNo || "";
      form.returnName = data.returnName || "";
      form.returnerId = data.returnerId || "";
      form.returnerName =
        data.returnerName || getReturnerNameById(data.returnerId);
      form.borrowOrderId = data.borrowOrderId || "";
      form.returnTime = data.returnTime
        ? new Date(data.returnTime).toISOString().slice(0, 19).replace("T", "T")
        : "";
      form.returnStatus = data.returnStatus ?? 0;
      form.remark = data.remark || "";

      // 加载对应的领用明细列表
      await loadBorrowDetails();

      // 回填明细信息
      form.details = (data.details || []).map((d: any) => ({
        id: d.id || 0,
        borrowDetailId: d.borrowDetailId || "",
        toolFixtureId: d.toolFixtureId || 0,
        toolFixtureName: d.toolFixtureName || "",
        storageLocationId: d.storageLocationId || 0,
        storageLocationName: d.storageLocationName || "",
        returnCount: d.returnCount || 1,
        toolStatusWhenReturn: d.toolStatusWhenReturn || "",
        checkerId: d.checkerId || "",
        remarkDetail: d.remarkDetali || "",
      }));

      // 刷新标签显示
      refreshDetailLabels();
    }
  } catch (e) {
    ElMessage.error("获取归还详情失败，请稍后重试");
    // 如果接口调用失败，尝试从路由参数获取基础信息（兼容处理）
    const q = route.query;
    if (q && q.returnNo) form.returnNo = String(q.returnNo);
    if (q && q.returnName) form.returnName = String(q.returnName);
    if (q && q.returnerId) {
      form.returnerId = Number(q.returnerId);
      form.returnerName = getReturnerNameById(form.returnerId);
    }
    if (q && q.borrowOrderId) form.borrowOrderId = Number(q.borrowOrderId);
    if (q && q.returnTime) form.returnTime = String(q.returnTime);
    if (q && q.returnStatus !== undefined)
      form.returnStatus = Number(q.returnStatus);
    if (q && q.remark) form.remark = String(q.remark);
  }
};

onMounted(async () => {
  const q = route.query;
  if (q && q.id) form.id = Number(q.id);

  await fetchReturnerList();
  await loadBorrowOrders();
  await Promise.all([fetchFixtureOptions(), fetchSeatOptions()]);

  if (form.id && form.id > 0) {
    await loadReturnOrderDetail(form.id);
  } else {
    if (q && q.returnNo) form.returnNo = String(q.returnNo);
    if (q && q.returnName) form.returnName = String(q.returnName);
    if (q && q.returnerId) {
      form.returnerId = Number(q.returnerId);
      form.returnerName = getReturnerNameById(form.returnerId);
    }
    if (q && q.borrowOrderId) form.borrowOrderId = Number(q.borrowOrderId);
    if (q && q.returnTime) form.returnTime = String(q.returnTime);
    if (q && q.returnStatus !== undefined)
      form.returnStatus = Number(q.returnStatus);
    if (q && q.remark) form.remark = String(q.remark);
  }
});
</script>

<style scoped>
.tool-return-add {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  background: radial-gradient(
      circle at 20% 20%,
      rgba(64, 158, 255, 0.12),
      transparent 45%
    ),
    radial-gradient(
      circle at 80% 0%,
      rgba(102, 177, 255, 0.18),
      transparent 55%
    ),
    #f5f7fa;
  min-height: calc(100vh - 32px);
  box-sizing: border-box;
}
.hero-wrapper {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 14px;
  border-radius: 16px;
  background: linear-gradient(135deg, #fefefe, #f3f8ff 65%, #edf4ff);
  border: 1px solid rgba(79, 143, 255, 0.2);
  box-shadow: 0 25px 60px rgba(40, 123, 255, 0.08);
  position: relative;
  overflow: hidden;
}
.hero-wrapper::after {
  content: "";
  position: absolute;
  right: -60px;
  top: -60px;
  width: 220px;
  height: 220px;
  background: radial-gradient(
    circle,
    rgba(64, 158, 255, 0.2),
    rgba(64, 158, 255, 0)
  );
}
.page-header {
  display: grid;
  grid-template-columns: minmax(260px, 1fr) minmax(220px, auto);
  gap: 12px 24px;
  background: rgba(255, 255, 255, 0.8);
  padding: 16px 20px;
  border-radius: 16px;
  border: 1px solid #edf2ff;
  box-shadow: 0 8px 20px rgba(64, 158, 255, 0.08);
  position: relative;
  overflow: hidden;
}
.page-header > div:first-child {
  min-width: 280px;
}
.page-header::after {
  content: "";
  position: absolute;
  inset: 0;
  border-radius: 16px;
  pointer-events: none;
}
.page-tags {
  display: flex;
  gap: 8px;
  margin-top: 8px;
  flex-wrap: wrap;
}
.progress-steps {
  padding: 20px 24px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid #edf2ff;
  backdrop-filter: blur(6px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.progress-steps :deep(.el-steps) {
  padding: 8px 0;
}

.progress-steps :deep(.el-step__title) {
  font-weight: 500;
  color: #303133;
}

.progress-steps :deep(.el-step__description) {
  color: #909399;
  font-size: 12px;
}
.tips-alert {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.tips-alert :deep(.el-alert__content) {
  padding: 8px 0;
}
.insight-panel {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 12px;
}
.insight-card {
  background: #fff;
  padding: 18px;
  border-radius: 12px;
  border: 1px solid #eef1f7;
  box-shadow: 0 4px 16px rgba(31, 45, 61, 0.08);
  display: flex;
  flex-direction: column;
  gap: 12px;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

.insight-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 24px rgba(31, 45, 61, 0.12);
  border-color: #c0c4cc;
}
.insight-card.primary {
  background: linear-gradient(135deg, #ecf5ff, #f0fff8);
  border: 1px solid rgba(64, 158, 255, 0.2);
}
.insight-icon {
  width: 38px;
  height: 38px;
  border-radius: 12px;
  background: rgba(64, 158, 255, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
}
.insight-card.primary .insight-icon {
  background: rgba(64, 158, 255, 0.25);
}
.insight-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.insight-label {
  font-size: 13px;
  color: #8c8c8c;
}
.insight-value {
  font-size: 26px;
  font-weight: 700;
  color: #1f2d3d;
}
.insight-tip {
  margin: 0;
  font-size: 12px;
  color: #a0a3b1;
}
.page-title h2 {
  margin: 0;
  font-size: 20px;
  color: #1f2d3d;
}
.page-title p {
  margin: 6px 0 0;
  color: #909399;
  font-size: 13px;
}
.header-meta {
  display: grid;
  grid-auto-flow: column;
  gap: 18px;
  align-items: center;
  flex-wrap: wrap;
}
.meta-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 120px;
}
.status-pill {
  padding: 10px 14px;
  border-radius: 14px;
  background: linear-gradient(135deg, #eef5ff, #f5fbff);
  border: 1px dashed rgba(64, 158, 255, 0.4);
}
.meta-status {
  display: flex;
  align-items: center;
  gap: 6px;
}
.status-hint {
  font-size: 12px;
  color: #8c8c8c;
}
.page-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 12px;
  grid-column: 1 / -1;
  margin-top: 8px;
}

.action-btn {
  padding: 10px 20px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.action-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.action-btn.primary-btn {
  background: linear-gradient(135deg, #409eff, #36cfc9);
  border: none;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.35);
}

.action-btn.primary-btn:hover {
  background: linear-gradient(135deg, #36cfc9, #67c23a);
  box-shadow: 0 6px 15px rgba(54, 207, 201, 0.4);
}
.meta-label {
  font-size: 12px;
  color: #a0a3b1;
}
.meta-value {
  font-size: 16px;
  color: #1f2d3d;
  font-weight: 600;
}
.meta-value.accent {
  color: #409eff;
}
.section-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 16px rgba(31, 45, 61, 0.08);
  backdrop-filter: blur(4px);
  transition: all 0.3s ease;
}

.section-card:hover {
  box-shadow: 0 6px 24px rgba(31, 45, 61, 0.12);
}

.section-card :deep(.el-card__header) {
  border-bottom: 2px solid #f0f2f5;
  padding: 18px 20px;
  background: linear-gradient(135deg, #fafbfc, #ffffff);
}
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #1f2d3d;
}
.section-icon {
  color: #409eff;
}
.section-subtitle {
  margin: 0;
  color: #a0a3b1;
  font-size: 13px;
}
.base-form {
  padding: 8px 0;
}

.base-form :deep(.el-form-item) {
  margin-bottom: 18px;
}

.base-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  padding-bottom: 4px;
}

.base-form :deep(.el-input),
.base-form :deep(.el-select),
.base-form :deep(.el-date-picker) {
  border-radius: 6px;
  transition: all 0.2s ease;
}

.base-form :deep(.el-input__wrapper),
.base-form :deep(.el-select__wrapper) {
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
  transition: all 0.2s ease;
}

.base-form :deep(.el-input__wrapper:hover),
.base-form :deep(.el-select__wrapper:hover) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.returner-input {
  display: flex;
  align-items: center;
  gap: 8px;
}
.returner-picker-btn {
  background: linear-gradient(135deg, #409eff, #36cfc9);
  border: none;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.35);
}
.returner-picker-btn:focus,
.returner-picker-btn:hover {
  background: linear-gradient(135deg, #36cfc9, #67c23a);
  box-shadow: 0 6px 15px rgba(54, 207, 201, 0.4);
}
.returner-picker-btn :deep(.el-icon) {
  font-size: 18px;
}
.detail-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 14px 16px;
  background: linear-gradient(135deg, #f8fafc, #ffffff);
  border-radius: 10px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.detail-toolbar:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-color: #c0c4cc;
}

.toolbar-left {
  display: flex;
  gap: 10px;
  align-items: center;
}

.toolbar-btn {
  padding: 8px 16px;
  font-weight: 500;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.toolbar-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 13px;
}

.toolbar-tag {
  border-radius: 6px;
  font-weight: 500;
  padding: 4px 10px;
}

.toolbar-tag strong {
  font-weight: 600;
  margin: 0 2px;
}
.summary-line {
  margin-top: 16px;
  padding: 14px 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  background: linear-gradient(135deg, #f8f9fa, #ffffff);
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
}

.summary-value {
  font-size: 20px;
  color: #409eff;
  font-weight: 700;
  letter-spacing: 0.5px;
}
.detail-table {
  border-radius: 8px;
  overflow: hidden;
}

.detail-table :deep(.el-table__header) {
  background: #f8f9fa;
}

.detail-table :deep(.el-table__header th) {
  background: #f8f9fa;
  color: #303133;
  font-weight: 600;
  border-bottom: 2px solid #e4e7ed;
  padding: 14px 0;
}

.detail-table :deep(.el-table__body tr:hover > td) {
  background: #f0f9ff !important;
}

.detail-table :deep(.el-table__body td) {
  padding: 12px 0;
  background: #fff;
  border-bottom: 1px solid #f0f2f5;
}

.detail-table :deep(.detail-row-warning td) {
  background: #fff7e6 !important;
  border-left: 3px solid #e6a23c;
}

.detail-table :deep(.detail-row-warning:hover td) {
  background: #fff4e0 !important;
}

.detail-table :deep(.detail-row-even td) {
  background: #fafbfc;
}

.detail-table :deep(.detail-row-odd td) {
  background: #fff;
}

.detail-table :deep(.el-table__row) {
  transition: all 0.2s ease;
}

.detail-table :deep(.el-table__row:hover) {
  transform: scale(1.001);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.delete-btn {
  padding: 4px 8px;
  font-weight: 500;
  transition: all 0.2s ease;
  border-radius: 4px;
}

.delete-btn:hover {
  background: #fef0f0;
  transform: translateY(-1px);
}
.footer-actions {
  position: sticky;
  bottom: 0;
  display: flex;
  justify-content: center;
  gap: 16px;
  padding: 20px 0;
  background: linear-gradient(180deg, rgba(245, 247, 250, 0), #f5f7fa 60%);
  border-top: 2px solid #e4e7ed;
  margin-top: 20px;
  z-index: 10;
}

.footer-btn {
  padding: 12px 32px;
  font-weight: 500;
  border-radius: 8px;
  transition: all 0.3s ease;
  min-width: 120px;
}

.footer-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.submit-btn {
  background: linear-gradient(135deg, #409eff, #36cfc9);
  border: none;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.35);
}

.submit-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #36cfc9, #67c23a);
  box-shadow: 0 6px 15px rgba(54, 207, 201, 0.4);
}
.manager-search {
  margin-bottom: 16px;
}

.search-input {
  border-radius: 8px;
}

.search-input :deep(.el-input__wrapper) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.user-dialog :deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
}

.user-dialog :deep(.el-dialog__header) {
  padding: 20px 24px;
  border-bottom: 2px solid #f0f2f5;
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.dialog-icon {
  font-size: 20px;
  color: #409eff;
}

.user-table {
  border-radius: 8px;
  overflow: hidden;
}

.user-table :deep(.el-table__header th) {
  background: #f8f9fa;
  color: #303133;
  font-weight: 600;
  border-bottom: 2px solid #e4e7ed;
}

.user-table :deep(.el-table__body tr:hover > td) {
  background: #f0f9ff !important;
}

.user-name-cell {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
}

.user-icon {
  font-size: 16px;
  color: #909399;
}

.select-btn {
  padding: 4px 12px;
  font-weight: 500;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.select-btn:hover {
  background: #ecf5ff;
  transform: translateY(-1px);
}
@media (max-width: 960px) {
  .page-header {
    grid-template-columns: 1fr;
  }
  .header-meta {
    width: 100%;
    gap: 12px;
    grid-auto-flow: row;
  }
  .meta-item {
    min-width: 0;
  }
  .detail-toolbar {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  .page-actions {
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  .insight-panel {
    grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
  }
  .footer-actions {
    flex-direction: column;
  }
}
</style>
